<template>
  <div class="user">
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24"
                :sm="24"
                :md="4"
                class="user__tree">
          <avue-tree :option="deptTreeOption"
                     :data="deptTreeData"
                     @node-click="nodeClick">
            <span class="el-tree-node__label"
                  slot-scope="{ node }">
              <span>
                <i class="el-icon-s-home"></i>
                {{node.label}}
              </span>
            </span>
          </avue-tree>
        </el-col>
        <el-col :xs="24"
                :sm="24"
                :md="20"
                class="user__main">
          <avue-crud ref="crud"
                     :option="option"
                     v-model="form"
                     :page.sync="page"
                     :table-loading="listLoading"
                     :before-open="handleOpenBefore"
                     :data="list"
                     :upload-after="uploadAfter"
                     @on-load="getList"
                     @search-change="searchChange"
                     @refresh-change="refreshChange"
                     @size-change="sizeChange"
                     @current-change="currentChange"
                     @row-update="update"
                     @row-save="create">
            <template slot="menuLeft">
              <el-button v-if="permissions.account_add"
                         class="filter-item"
                         type="primary"
                         size="small"
                         icon="el-icon-plus"
                         @click="handleCreate()">添加
              </el-button>
            </template>
            <template slot="roles"
                      slot-scope="scope">
              <span v-for="(role,index) in scope.row.roles"
                    :key="index">
                <el-tag>{{ role.roleName }}</el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="deptId"
                      slot-scope="scope">
              <el-tag>{{ scope.row.deptName }}</el-tag>
            </template>
            <template slot-scope="scope"
                      slot="menuBtn">
              <el-dropdown-item v-if="permissions.account_edit"
                                divided
                                icon="el-icon-edit"
                                @click.native="handleUpdate(scope.row,scope.index)">编辑
              </el-dropdown-item>
              <el-dropdown-item v-if="permissions.account_del"
                                divided
                                icon="el-icon-delete"
                                @click.native="deletes(scope.row,scope.index)">删除
              </el-dropdown-item>
              <el-dropdown-item v-if="permissions.account_edit_email"
                                divided
                                icon="el-icon-edit"
                                @click.native="handleEditSimpleForm(scope.row,'email','修改邮箱--')">修改邮箱
              </el-dropdown-item>
              <el-dropdown-item v-if="permissions.account_edit_username_password"
                                divided
                                icon="el-icon-edit"
                                @click.native="handleEditSimpleForm(scope.row,'usernamePassword','修改账号密码--')">修改账号密码
              </el-dropdown-item>
              <el-dropdown-item v-if="permissions.account_edit_phone"
                                divided
                                icon="el-icon-edit"
                                @click.native="handleEditSimpleForm(scope.row,'phone','修改手机号码--')">修改手机号码
              </el-dropdown-item>
            </template>
            <template slot="deptIdForm">
              <avue-input-tree v-model="form.deptId"
                               :disabled="viewDisabled"
                               :dic="deptTreeData"
                               :props="deptTreeOption.props"
                               placeholder="请选择所属部门" />
            </template>
            <template slot="rolesForm">
              <el-select v-model="form.roles"
                         :disabled="viewDisabled"
                         placeholder="请选择角色"
                         multiple>
                <el-option-group v-for="group in rolesOptions"
                                 :key="group.label"
                                 :label="group.label">
                  <el-option v-for="item in group.options"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-option-group>
              </el-select>
            </template>
          </avue-crud>
        </el-col>
      </el-row>

      <el-dialog :title="editSimpleForm.title"
                 :visible.sync="dialogVisible"
                 :close-on-click-modal="false"
                 append-to-body
                 width="25%">
        <el-form ref="editSimpleForm"
                 :rules="editSimpleFormRules"
                 :model="editSimpleForm"
                 label-width="80px">
          <el-form-item label="邮箱"
                        prop="email"
                        v-if="editSimpleForm.type === 'email'">
            <el-input placeholder="请输入邮箱"
                      suffix-icon="el-icon-s-promotion"
                      v-model="editSimpleForm.email">
            </el-input>
          </el-form-item>
          <el-form-item label="手机号码"
                        prop="phone"
                        v-if="editSimpleForm.type === 'phone'">
            <el-input placeholder="请输入手机号码"
                      suffix-icon="el-icon-phone-outline"
                      v-model="editSimpleForm.phone">
            </el-input>
          </el-form-item>
          <el-form-item label="账号"
                        prop="username"
                        v-if="editSimpleForm.type === 'usernamePassword'">
            <el-input placeholder="请输入账号"
                      suffix-icon="el-icon-user"
                      v-model="editSimpleForm.username">
            </el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password"
                        v-if="editSimpleForm.type === 'usernamePassword'">
            <el-input placeholder="请输入密码"
                      suffix-icon="el-icon-lock"
                      v-model="editSimpleForm.password">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="saveEditSimpleForm()">确 定</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { addObj, delObj, fetchList, putObj, editEmail, editPhone, editUsernamePassword } from '@/api/admin/user'
import { roleGroup } from '@/api/admin/role'
import { fetchTree } from '@/api/admin/sys-tree'
import { tableOption } from '@/const/crud/admin/user'
import { mapGetters } from 'vuex'
import { validateEmail, isvalidatemobile, validatenull } from '@/util/validate'
import { encryptAES } from '@/util/util'

export default {
  name: 'Account',
  data () {
    return {
      searchForm: {},//搜索参数
      deptTreeOption: { //左侧部门选项
        filterText: '过滤部门',
        nodeKey: 'id',
        addBtn: false,
        menu: false,
        props: {
          label: 'name',
          value: 'id'
        }
      },
      deptTreeData: [],//部门数据
      roleProps: {//角色属性
        label: 'roleName',
        value: 'roleId'
      },
      rolesOptions: [],//角色列表
      option: tableOption,//表格选项
      page: {//分页参数
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false// 是否倒序
      },
      list: [],//表格数据列表
      listLoading: true,
      form: {},//表单数据
      viewDisabled: false,
      dialogVisible: false,
      editSimpleForm: {
        type: undefined,
        title: undefined,
        accountId: undefined,
        email: undefined,
        phone: undefined,
        usernmae: undefined,
        password: undefined
      },
      editSimpleFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (validateEmail(value)) {
                callback()
              } else {
                callback(new Error('邮箱格式有误'))
              }
            }, trigger: 'blur'
          }],
        phone: [
          { required: true, message: '请输入手机号', trigger: "blur" },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let result = isvalidatemobile(value)
              if (!result[0]) {
                callback()
              } else {
                callback(new Error(result[1]))
              }
            }, trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度最少为6位", trigger: "blur" },
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions'])//权限列表
  },
  watch: {
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      // 加载部门列表
      fetchTree({ treeType: 1 }).then(response => {
        this.deptTreeData = response.data.data
      })
      // 加载角色列表
      roleGroup().then(response => {
        this.rolesOptions = response.data.data
      })
    },
    nodeClick (data) {//选中左侧部门
      this.page.currentPage = 1
      this.getList(this.page, { deptId: data.id })
    },
    getList (page, params) {
      this.listLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.list = response.data.data.records
        this.page.total = response.data.data.total
        this.listLoading = false
      })
    },
    searchChange (param, done) {
      this.searchForm = param
      this.page.currentPage = 1
      this.getList(this.page, param)
      done()
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange (current) {
      this.page.currentPage = current
    },
    refreshChange () {
      this.getList(this.page)
    },
    handleOpenBefore (show, type) {
      window.boxType = type
      if (['edit', 'view'].includes(type)) {
        let roles = []
        for (let i = 0; i < this.form.roles.length; i++) {
          roles[i] = this.form.roles[i].roleId
        }
        this.form.roles = roles
      }
      if ('view' == type) {
        this.viewDisabled = true
      } else {
        this.viewDisabled = false
      }
      show()
    },
    handleCreate () {
      this.$refs.crud.rowAdd()
    },
    handleUpdate (row, index) {
      this.$refs.crud.rowEdit(row, index)
    },
    handleEditSimpleForm (row, type, titile) {
      this.dialogVisible = true
      this.clearEditSimpleFormValid()
      this.editSimpleForm = {
        type: type,
        title: titile + row.nickname,
        accountId: row.accountId,
        phone: row.phone,
        email: row.email,
        username: row.username,
        password: undefined
      }
    },
    saveEditSimpleForm () {
      if (this.editSimpleForm.type === 'email') {
        this.editEmail()
      }
      if (this.editSimpleForm.type === 'phone') {
        this.editPhone()
      }
      if (this.editSimpleForm.type === 'usernamePassword') {
        this.editUsernamePassword()
      }
    },
    clearEditSimpleFormValid () {
      this.$nextTick(() => {
        this.$refs['editSimpleForm'].clearValidate(['email', 'phone', 'username', 'password'])
      })
    },
    editEmail () {
      this.$refs['editSimpleForm'].validate((valid) => {
        if (valid) {
          editEmail(this.editSimpleForm).then(resp => {
            this.dialogVisible = false
            this.$notify.success(resp.data.message)
            this.getList(this.page)
          })
        }
      })
    },
    editPhone () {
      this.$refs['editSimpleForm'].validate((valid) => {
        if (valid) {
          editPhone(this.editSimpleForm).then(resp => {
            this.dialogVisible = false
            this.$notify.success(resp.data.message)
            this.getList(this.page)
          })
        }
      })
    },
    editUsernamePassword () {
      this.$refs['editSimpleForm'].validate((valid) => {
        if (valid) {
          editUsernamePassword(Object.assign(this.editSimpleForm, { password: encryptAES(this.editSimpleForm.password) })).then(resp => {
            this.dialogVisible = false
            this.$notify.success(resp.data.message)
            this.getList(this.page)
          })
        }
      })
    },
    create (row, done, loading) {
      addObj(this.form).then((resp) => {
        this.getList(this.page)
        done()
        this.$notify.success(resp.data.message)
      }).catch(() => {
        loading()
      })
    },
    update (row, index, done, loading) {
      putObj(this.form).then((resp) => {
        this.getList(this.page)
        done()
        this.$notify.success(resp.data.message)
      }).catch(() => {
        loading()
      })
    },
    deletes (row, index) {
      this.$confirm('此操作将永久删除该用户(用户名:' + row.nickname + '), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      ).then(() => {
        delObj(row.accountId)
          .then((resp) => {
            this.list.splice(index, 1)
            this.$notify.success(resp.data.message)
          }).catch((message) => {
            this.$notify.error(message)
          })
      })
    },
    uploadAfter (res, done, loading) {
      if (!validatenull(res.fileName)) {
        this.$message.success("头像上传成功");
      }
      done();
    },
  }
}
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>

